package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询探店笔记
     */
    @Override
    public Result queryBlogById(Long id) {

        Blog blog = query().eq("id", id).select(Blog.class, info -> !info.getColumn().equals("content")).one();
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        // 判断当前用户是否已经点赞
        String key = "blog:liked:" + blog.getId();
        UserDTO currentUser = UserHolder.getUser();
        if (currentUser == null) {
            // 未登录，无需查询是否已经点赞
            return Result.fail("用户未登录");
        }
        Double isLiked = stringRedisTemplate.opsForZSet().score(key, currentUser.getId().toString());
        blog.setIsLike(isLiked != null);

        return Result.ok(blog);

    }

    /**
     * 修改点赞数量
     */
    @Override
    public Result updateLike(Long id) {

        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();

        // 2.判断当前用户是否已经点赞
        String key = "blog:liked:" + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());

        if (score == null) {
            // 3.如果未点赞，可以点赞
            // 3.1数据库点赞数+1
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            if (update) {
                // 3.2保存用户到redis zset集合
                stringRedisTemplate.opsForZSet().add(key, user.getId().toString(), System.currentTimeMillis());
            }
        }
        else{
            // 4.如果已点赞，取消点赞
            // 4.1数据库点赞数-1
            boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            if (update) {
                // 4.2删除用户
                stringRedisTemplate.opsForZSet().remove(key, user.getId().toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询笔记点赞时间前5
     */
    @Override
    public Result queryBlogLikes(Long id) {

        // 1.查询top5的id
        String key = "blog:liked:" + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            // 返回空集合
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream()
                .map(Long::valueOf) // .map(Long::valueOf)的意思是对集合中的每个元素都执行Long::valueOf这个函数
                .collect(Collectors.toList());

        // 2.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
